import {
  CarInfoRecord,
  EntInfoRecord,
  PersonInfoRecord,
  deleteEnt,
  getCarList,
  getEntList,
  getPersonList
} from '@/api/codeServer'
import { Phone } from '@/components/PhoneInput'
import useNewDictData from '@/hooks'
import { Button, Modal, message } from 'antd'
import { useState } from 'react'
import { type YmTablePorps } from 'ym-design'
import { TreePopProps } from './modal/ChoiceCompany'

type TConfig = {
  tabKey: '1' | '2' | '3'
  modalRef: TreePopProps['innerRef']
  associationId?: string
  showPersonModal(entId: string): void
  showCarModal(entId: string): void
}

export function useTableConfig(config: TConfig) {
  const { tabKey, modalRef, associationId, showPersonModal, showCarModal } =
    config

  const [fresh, refresh] = useState(0)

  const [carTypeList] = useNewDictData<{
    label: string
    value: string
    key: string
  }>(108, (v) => ({ label: v.name, value: v.code, key: v.guid }))
  const [plateColorList] = useNewDictData<{
    label: string
    value: string
    key: string
  }>(88, (v) => ({ label: v.name, value: v.code, key: v.guid }))

  const entTableConfig: YmTablePorps<EntInfoRecord> = {
    searchForm: {
      formItems: [
        {
          label: '企业名称',
          name: 'entName',
          valueType: {
            type: 'input',
            inputProps: {
              placeholder: '请输入',
              allowClear: true
            }
          }
        }
      ],
      span: 6
    },
    request: async ({ page }, searchValue) => {
      const { entName } = searchValue as any
      const { pageIndex = 1, pageSize = 10 } = page ?? {}
      if (associationId) {
        const { list, total } = await getEntList({
          associationId,
          entName,
          pageIndex,
          pageSize
        })
        return {
          list,
          total
        }
      }
      return {
        list: [],
        total: 0
      }
    },
    requestOptions: {
      reFreshDep: [associationId, fresh, tabKey]
    },
    columns: [
      {
        title: '企业名称',
        dataIndex: 'entName',
        key: 'entName',
        width: 160,
        ellipsis: true
      },
      {
        title: '企业用户',
        dataIndex: 'staffCount',
        key: 'staffCount',
        width: 100
        // render(value, record) {
        //   return (
        //     <Button type="link" onClick={() => showPersonModal(record.entId)}>
        //       {value}
        //     </Button>
        //   )
        // }
      },
      {
        title: '司机用户',
        dataIndex: 'driverCount',
        key: 'driverCount',
        width: 100
        // render(value, record) {
        //   return (
        //     <Button type="link" onClick={() => showPersonModal(record.entId)}>
        //       {value}
        //     </Button>
        //   )
        // }
      },
      {
        title: '车辆',
        dataIndex: 'carCount',
        key: 'carCount',
        width: 100
        // render(value, record) {
        //   return (
        //     <Button type="link" onClick={() => showCarModal(record.entId)}>
        //       {value}
        //     </Button>
        //   )
        // }
      },
      {
        title: '已备案人员',
        dataIndex: 'registerPersonCount',
        key: 'registerPersonCount',
        width: 120,
        render(value, record) {
          return (
            <Button type="link" onClick={() => showPersonModal(record.entId)}>
              {value}
            </Button>
          )
        }
      },
      {
        title: '已备案车辆',
        dataIndex: 'registerCarCount',
        key: 'registerCarCount',
        width: 120,
        render(value, record) {
          return (
            <Button type="link" onClick={() => showCarModal(record.entId)}>
              {value}
            </Button>
          )
        }
      },
      {
        width: 80,
        title: '操作',
        key: 'action',
        render: (_, record) => (
          <a
            onClick={() => {
              Modal.confirm({
                title: '确定删除吗？',
                centered: true,
                onOk() {
                  deleteEnt({
                    entId: record.entId,
                    associationId: associationId!
                  }).then((data) => {
                    data &&
                      message.open({
                        type: 'success',
                        content: '操作成功'
                      })
                    refresh(Math.random())
                  })
                }
              })
            }}
          >
            删除
          </a>
        )
      }
    ],
    toolBar: {
      prefixNode: (
        <Button
          onClick={() => {
            if (!associationId) {
              message.open({
                type: 'warning',
                content: '请先选择协会'
              })
              return
            }
            modalRef?.current?.showModal()
          }}
          type="primary"
        >
          新增企业
        </Button>
      )
    }
    // operate: [ // 不生效？？
    //   {
    //     text: '删除',
    //     key: 'del',
    //     onClick(record) {
    //       console.log(record)
    //     }
    //   }
    // ]
  }

  const personelTableConfig: YmTablePorps<PersonInfoRecord> = {
    searchForm: {
      formItems: [
        {
          label: '姓名',
          name: 'name',
          valueType: {
            type: 'input',
            inputProps: {
              placeholder: '请输入',
              allowClear: true
            }
          }
        },
        {
          label: '手机号',
          name: 'phone',
          children: <Phone />
        }
      ],
      span: 6
    },
    request: async ({ page }, searchValue) => {
      const { name, phone } = searchValue as any
      const { pageIndex = 1, pageSize = 10 } = page ?? {}
      if (associationId) {
        const { list, total } = await getPersonList({
          associationId,
          name,
          phone,
          pageIndex,
          pageSize
        })
        return {
          list,
          total
        }
      }
      return {
        list: [],
        total: 0
      }
    },
    requestOptions: {
      reFreshDep: [associationId, fresh, tabKey]
    },
    columns: [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 140,
        ellipsis: true
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        width: 100
      },
      {
        title: '备案时关联的企业',
        dataIndex: 'joinList',
        key: 'joinList',
        width: 140,
        render(value: PersonInfoRecord['joinList']) {
          return value?.map((item) => item.name).join('，') || '暂无企业'
        }
      },
      {
        title: '备案时间',
        dataIndex: 'dateTime',
        key: 'dateTime',
        width: 140
      }
    ]
  }

  const carTableConfig: YmTablePorps<CarInfoRecord> = {
    searchForm: {
      formItems: [
        {
          label: '车牌号',
          name: 'carBrand',
          valueType: {
            type: 'input',
            inputProps: {
              placeholder: '请输入',
              allowClear: true
            }
          }
        },
        {
          label: '车辆类型',
          name: 'carType',
          valueType: {
            type: 'select',
            selectProps: {
              options: carTypeList,
              placeholder: '请选择',
              allowClear: true
            }
          }
        },
        {
          label: '车牌颜色',
          name: 'plateColor',
          valueType: {
            type: 'select',
            selectProps: {
              options: plateColorList,
              placeholder: '请选择',
              allowClear: true
            }
          }
        }
      ],
      span: 6
    },
    request: async ({ page }, searchValue) => {
      const { carBrand, carType, plateColor } = searchValue as any
      const { pageIndex = 1, pageSize = 10 } = page ?? {}
      if (associationId) {
        const { list, total } = await getCarList({
          associationId,
          carBrand,
          carType,
          plateColor,
          pageIndex,
          pageSize
        })
        return {
          list,
          total
        }
      }
      return {
        list: [],
        total: 0
      }
    },
    requestOptions: {
      reFreshDep: [associationId, fresh, tabKey]
    },
    columns: [
      {
        title: '车牌号',
        dataIndex: 'carBrand',
        key: 'carBrand',
        width: 100,
        ellipsis: true
      },
      {
        title: '车辆类型',
        dataIndex: 'carType',
        key: 'carType',
        width: 100,
        render(value) {
          return (
            carTypeList?.find((item) => item.value === value)?.label ?? '--'
          )
        }
      },
      {
        title: '车辆颜色',
        dataIndex: 'plateColor',
        key: 'plateColor',
        width: 100
      },
      {
        title: '备案时关联的企业/个人',
        dataIndex: 'belongObjectNames',
        key: 'belongObjectNames',
        width: 140
      },
      {
        title: '备案时间',
        dataIndex: 'dateTime',
        key: 'dateTime',
        width: 140
      }
    ]
  }

  const tableConfigMap = {
    '1': entTableConfig,
    '2': personelTableConfig,
    '3': carTableConfig
  }

  return {
    tableProps: tableConfigMap[tabKey],
    refresh
  }
}
